package base.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * base 基本样例
 * 消费者
 * 1.负载均衡模式(默认) MessageModel.CLUSTERING
 * 2.广播模式  MessageModel.BROADCASTING
 * @author: BacHe
 * @email: 1218585258@qq.com
 * @Date: 2020/12/7 23:14
 */
public class Consumer {
    public static void main(String[] args) throws MQClientException {
        //1.创建消费者consumer，指定消费者组
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
        //2.指定nameserver地址
        consumer.setNamesrvAddr("47.107.104.169:9876");
        //3.订阅主题Topic 和 tag  （tag 可以用 || 表达式 ，也可以用 * ）
        consumer.subscribe("topic1","*");
        //broadcasting 广播
        //clustering 集群负载均衡（默认）
//        consumer.setMessageModel(MessageModel.BROADCASTING);
        consumer.setMessageModel(MessageModel.CLUSTERING);
        //4.设置回调函数，处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                list.forEach(messageExt -> {
                    System.out.println("consumeMessage:" + new String(messageExt.getBody()));
                });
                //返回消费成功
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //5.启动消费者consumer
        consumer.start();



    }
}
